package com.itheima.app.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.itheima.app.manager.UserManager;
import com.itheima.domain.db.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author 请不要叫我高司令
 * @Date 2022/3/14 22:16
 * @Version 1.0
 */


@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private UserManager userManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("Authorization");
        User user = userManager.findUserByToken(token);
        if (ObjectUtil.isEmpty(user)) {
            //401权限不足
            response.setStatus(401);
            return false;
        }

        UserHolder.set(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        //等出移除user
        UserHolder.remove();


    }
}
